package com.chuantou.yuba.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.chuantou.yuba.db.columns.CacheColumns;
import com.chuantou.yuba.db.util.CursorHelper;
import com.chuantou.yuba.db.util.SqliteWrapper;
import com.chuantou.yuba.pojo.Cache;
import com.chuantou.yuba.pojo.Cacheable;
import com.google.gson.Gson;

/**
 * 缓存操作TO
 * 
 * @author dl1001
 * 
 */
public class CacheDao {

	/**
	 * 获取缓存
	 * 
	 * @param cacheKey
	 * @param clazz
	 * @return
	 */
	public static <T extends Cacheable> Cache<T> getCache(Context context, String cacheKey, Class<T> clazz) {
		Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(), CacheColumns.CONTENT_URI, null, CacheColumns.COLUMNS_CACHE_KEY + "=?",
				new String[] { cacheKey }, null);
		Cache<T> cache = null;
		if (cursor != null) {
			if (cursor.moveToFirst()) {
				cache = readFromCursor(cursor, clazz);
			}
			cursor.close();
		}
		return cache;
	}

	/**
	 * 新增或者更新缓存
	 * 
	 * @param context
	 * @param cacheKey
	 * @param cacheable
	 */
	public static <T extends Cacheable> int addOrUpdateCache(Context context, String cacheKey, Cacheable cacheable) {
		ContentValues values = new ContentValues();
		String cacheContent = cacheable.dumpCache();
		values.put(CacheColumns.COLUMNS_DATA, cacheContent.getBytes());
		values.put(CacheColumns.COLUMNS_TIME, System.currentTimeMillis());
		// 更新不成功 ，然后执行插入操作
		int count = SqliteWrapper.update(context, context.getContentResolver(), CacheColumns.CONTENT_URI, values, CacheColumns.COLUMNS_CACHE_KEY + "=?",
				new String[] { cacheKey });
		if (count <= 0) {
			values.put(CacheColumns.COLUMNS_CACHE_KEY, cacheKey);
			SqliteWrapper.insert(context, context.getContentResolver(), CacheColumns.CONTENT_URI, values);
			count = 1;
		}
		return count;
	}

	private static final <T extends Cacheable> Cache<T> readFromCursor(Cursor cursor, Class<T> clazz) {
		try {
			byte[] data = CursorHelper.getBlob(cursor, CacheColumns.COLUMNS_DATA);
			if (data == null || data.length == 0) {
				return null;
			}
			Cache<T> cache = new Cache<T>();
			String cacheKey = CursorHelper.getString(cursor, CacheColumns.COLUMNS_CACHE_KEY, null);
			long time = CursorHelper.getLong(cursor, CacheColumns.COLUMNS_TIME, 0);
			String cacheContent = new String(data);
			Gson gson = new Gson();
			T cacheData = gson.fromJson(cacheContent, clazz);
			cache.setCacheKey(cacheKey);
			cache.setCacheTime(time);
			cache.setData(cacheData);
			return cache;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
